var dateLong= require('../utils/dateLong.js');
var app = getApp();

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}
function format(shijianchuo, type) {
  //shijianchuo是整数，否则要parseInt转换
  var time = new Date(shijianchuo);
  var y = time.getFullYear();
  var m = time.getMonth() + 1;
  var d = time.getDate();
  var h = time.getHours();
  var mm = time.getMinutes();
  var s = time.getSeconds();
  if (type == 'yyyy-MM-dd') {
    return y + '-' + add0(m) + '-' + add0(d);
  } else {
    return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s);
  }
}
function add0(m) { return m < 10 ? '0' + m : m }

 function  format2 (time, str) {
  if (time == "" || time == null) {
    return "";
  }
      var  t  =  new  Date(time);
      var  tf  =  function (i) { return  (i  <  10  ?  '0'  :  '')  +  i };
      return str.replace("/yyyy|MM|dd|HH|mm|ss/g",  function (a) {
            switch (a) {
                  case  'yyyy':
                        return  tf(t.getFullYear());
                        break;
                  case  'MM':
                        return  tf(t.getMonth()  +  1);
                        break;
                  case  'mm':
                        return  tf(t.getMinutes());
                        break;
                  case  'dd':
                        return  tf(t.getDate());
                        break;
                  case  'HH':
                        return  tf(t.getHours());
                        break;
                  case  'ss':
                        return  tf(t.getSeconds());
                        break;
            }
      })
}
function datetimeFormat(longTypeDate) {
  var dateTypeDate = "";
  var date = new Date();
  date.setTime(longTypeDate);
  dateTypeDate += date.getFullYear(); //年  
  dateTypeDate += "-" + dateLong.getMonth(date); //月  
  dateTypeDate += "-" + dateLong.getDay(date); //日  
  dateTypeDate += " " + dateLong.getHours(date); //时  
  dateTypeDate += ":" + dateLong.getMinutes(date);  //分 
  dateTypeDate += ":" + dateLong.getSeconds(date);  //分 
  return dateTypeDate;
} 

var rootDocment = 'https://fangdong.kuailezufang.com' //'https://fangdong.kuailezufang.com';landlord.kuailezufang.comhttps://landlord.kuailezufang.com
var shareUtil ="http://zuke.kuailezufang.com/html/house/homeDetail.html?type=xcx";
var userInfo="";
//修改成你的appid及appsecret
var AppConf = { 'appid': 'wx25e03ff4a97ca181', 'appsecret': 'b9be9053c8cd95e4aab3e6ef2f41a8ad' };
    
function req(url, data, cb) {
  data.appid = AppConf.appid;
  data.appsecret = AppConf.appsecret;
  data.is_ajax_req = '1'
  wx.request({
    url: rootDocment + url,
    data: data,
    method: 'post',
    dataType: 'json',
    cache: false,
    header: { 'Content-Type': 'application/x-www-form-urlencoded' },
    success: function (res) {
      
      return typeof cb == "function" && cb(res.data)
    },
    fail: function (res) {
      var content='';
      if (res.errMsg){
        content = res.errMsg;
        wx.showModal({
          title: '错误',
          content: content,
          mode: true,
          showCancel: false,
          confirmColor: '#007aff',
        })
        return false;
      }else{
        content='网络连接失败';
        wx.showModal({
          title: '错误',
          content: content,
          mode: true,
          showCancel: false,
          confirmColor: '#007aff',
        })
        return false;
      }
     
      return typeof cb == "function" && cb(false)
    }
  })
}

function getReq(url, data, cb) {
  var that = this;
  wx.getStorage({
    key: 'userInfo',
    success: function (res) {
      data.source = res.data.source;
      data.uid = res.data.user_id;
      data.phone_num = res.data.phone_num;
    }
  });
  data.appid = AppConf.appid;
  data.appsecret = AppConf.appsecret;
  data.is_ajax_req = '1';
  wx.getStorage({
    key: 'userInfo',
    success: function (res) {
      let userInfo= res.data;
      let sessionId = '';
      wx.getStorage({
        key: 'sessionId',
        success: function (res) {
          sessionId = res.data;
          wx.request({
            url: rootDocment + url,
            data: data,
            method: 'post',
            async: false,
            header: { 'Content-Type': 'application/x-www-form-urlencoded', 'Cookie': 'JSESSIONID =' + sessionId },
            success: function (res) {
              if (res && res.data.code == 301) {
                wx.redirectTo({
                  url: '/pages/index/index',
                })
                return false;
              }

              return typeof cb == "function" && cb(res.data)
            },
            fail: function (res) {
              if (res.desc) {
                wx.showModal({
                  title: '错误',
                  content: res.desc,
                  mode: true,
                  showCancel: false,
                  confirmColor: '#007aff',
                })
                return false;
              } else if (res.errMsg) {

                wx.showModal({
                  title: '错误',
                  content: res.errMsg,
                  mode: true,
                  showCancel: false,
                  confirmColor: '#007aff',
                })
                return false;
              }

              return typeof cb == "function" && cb(false)
            }
          })
        },
        fail: function () {
          wx.redirectTo({
            url: '/pages/index/index',
          })
        }
      })
    },
    fail:function(){
      wx.redirectTo({
        url: '/pages/index/index',
      })
    }
  })
 
  
}

function getReqJsonp(url, data, cb) {
  data.appid = AppConf.appid;
  data.appsecret = AppConf.appsecret;
  wx.getStorage({
    key: 'userInfo',
    success: function (res) {
      userInfo = res.data;
    },
    fail: function () {
      wx.redirectTo({
        url: '../pages/index/index',
      })
    }
  })
  wx.request({
    url: rootDocment + url,
    data: data,
    method: 'post',
    dataType:'json',
    header: { 'Content-Type': 'application/x-www-form-urlencoded' },
    success: function (res) {
      return typeof cb == "function" && cb(res.data)
    },
    fail: function () {
      wx.hideLoading();
      wx.showModal({
        title: '错误',
        content: res,
        mode: true,
        showCancel: false,
        confirmColor: '#007aff',
      })
      return typeof cb == "function" && cb(false)
    }
  })
}

// 去前后空格  
function trim(str) {
  return str.replace(/(^\s*)|(\s*$)/g, "");
}

// 提示错误信息  
function isError(msg) {
  wx.showModal({
    title: '错误',
    content: msg,
    mode: true,
    showCancel: false,
    confirmColor: '#007aff',
  })
}

// 清空错误信息  
function clearError(that) {
  that.setData({
    showTopTips: false,
    errorMsg: ""
  })
}

function getDateDiff(dateTimeStamp) {
  var minute = 1000 * 60;
  var hour = minute * 60;
  var day = hour * 24;
  var halfamonth = day * 15;
  var month = day * 30;
  var now = new Date().getTime();
  var diffValue = dateTimeStamp - now;
  if (diffValue < 0) { return; }
  var monthC = diffValue / month;
  var weekC = diffValue / (7 * day);
  var dayC = diffValue / day;
  var hourC = diffValue / hour;
  var minC = diffValue / minute;
  var result = '';
  if (monthC >= 1) {
    result = "" + parseInt(monthC) + "月后";
  }
  else if (weekC >= 1) {
    result = "" + parseInt(weekC) + "周后";
  }
  else if (dayC >= 1) {
    result = "" + parseInt(dayC) + "天后";
  }
  else if (hourC >= 1) {
    result = "" + parseInt(hourC) + "小时后";
  }
  else if (minC >= 1) {
    result = "" + parseInt(minC) + "分钟后";
  } else
    result = "刚刚";
  return result;
}

function getDateBiff(dateTimeStamp) {
  var minute = 1000 * 60;
  var hour = minute * 60;
  var day = hour * 24;
  var halfamonth = day * 15;
  var month = day * 30;
  var now = new Date().getTime();
  var diffValue = now - dateTimeStamp;
  if (diffValue < 0) { return; }
  var monthC = diffValue / month;
  var weekC = diffValue / (7 * day);
  var dayC = diffValue / day;
  var hourC = diffValue / hour;
  var minC = diffValue / minute;
  var result = '';
  if (monthC >= 1) {
    result = "" + parseInt(monthC) + "月前";
  }
  else if (weekC >= 1) {
    result = "" + parseInt(weekC) + "周前";
  }
  else if (dayC >= 1) {
    result = "" + parseInt(dayC) + "天前";
  }
  else if (hourC >= 1) {
    result = "" + parseInt(hourC) + "小时前";
  }
  else if (minC >= 1) {
    result = "" + parseInt(minC) + "分钟前";
  } else
    result = "刚刚";
  return result;
}

function escape2Html(str) {
  var arrEntities = { 'lt': '<', 'gt': '>', 'nbsp': ' ', 'amp': '&', 'quot': '"' };
  return str.replace(/&(lt|gt|nbsp|amp|quot);/ig, function (all, t) { return arrEntities[t]; });
}

function loading(){
  wx.showLoading({
    title: '加载中请稍后...',
  })
}

function closeloading(){
  setTimeout(function () {
    wx.hideLoading()
  }, 1000)  
}

module.exports = {
  formatTime: formatTime,
  req: req,
  trim: trim,
  isError: isError,
  clearError: clearError,
  getReq: getReq,
  getDateDiff: getDateDiff,
  escape2Html: escape2Html,
  getDateBiff: getDateBiff,
  format: format,
  getReqJsonp: getReqJsonp,
  format2: format2,
  loading: loading,
  closeloading: closeloading,
  datetimeFormat: datetimeFormat,
  shareUtil: shareUtil
}  